/**
 * Created by Toma on 2016/11/21.
 * 折线图
 */

var H5ComponentRadar = function (name, cfg) {
  var compontent = new H5ComonentBase(name, cfg);

  // 绘制网格线
  var WIDTH = cfg.width;
  var HEIGHT = cfg.height;

  // 添加画布
  var cns = document.createElement('canvas');
  var ctx = cns.getContext('2d');
  cns.width = ctx.width = WIDTH;
  cns.height = ctx.height = HEIGHT;
  compontent.append(cns);

  var step = cfg.data.length;
  var r = WIDTH / 2;
  var isBlue = false;
  // 绘制网格背景
  for (var s = 10; s > 0; s--) {
    ctx.beginPath();
    ctx.fillStyle = (isBlue = !isBlue) ? '#99c0ff' : '#f1f9ff';
    for (var i = 0; i < step; i++) {
      var rad = (2 * Math.PI / step) * i;
      var x = r + Math.sin(rad) * r * (s / 10);
      var y = r + Math.cos(rad) * r * (s / 10);
      ctx.lineTo(x, y);
    }
    ctx.closePath();
    ctx.fill();
  }

  // 绘制伞架
  ctx.beginPath();
  for (var i = 0; i < step; i++) {
    var rad = (2 * Math.PI / step) * i;
    var x = r + Math.sin(rad) * r;
    var y = r + Math.cos(rad) * r;
    ctx.moveTo(r, r);
    ctx.lineTo(x, y);
    // 输出文字
    var text = $('<div class="text">');
    text.text(cfg.data[i][0]);
    x > WIDTH / 2 ? text.css('left', x / 2) : text.css('right', (WIDTH - x) / 2);
    y > HEIGHT / 2 ? text.css('top', y / 2) : text.css('bottom', (HEIGHT - y) / 2);
    cfg.data[i][2] && text.css('color',cfg.data[i][2]);
    compontent.append(text);
  }
  ctx.strokeStyle = '#f1f9ff';
  ctx.lineWidth = 2;
  ctx.stroke();


  /**
   * 绘制折线
   * @param per 传入百分比
   */
  var cns = document.createElement('canvas');
  var ctx = cns.getContext('2d');
  cns.width = ctx.width = WIDTH;
  cns.height = ctx.height = HEIGHT;
  compontent.append(cns);

  var draw = function (per) {
    ctx.clearRect(0, 0, WIDTH, HEIGHT);
    // 输出数据的折线
    ctx.beginPath();
    ctx.strokeStyle = '#F00';
    for (var i = 0; i < step; i++) {
      var rad = (2 * Math.PI / step) * i;
      var rate = cfg.data[i][1] * per;
      var x = r + Math.sin(rad) * r * rate;
      var y = r + Math.cos(rad) * r * rate;
      ctx.lineTo(x, y);
    }
    ctx.closePath();
    ctx.stroke();
    ctx.fillStyle = 'rgba(255,0,0,.4)'
    ctx.fill();
    // 输出点
    for (var i = 0; i < step; i++) {
      ctx.beginPath();
      ctx.fillStyle = '#F00';
      var rad = (2 * Math.PI / step) * i;
      var rate = cfg.data[i][1] * per;
      var x = r + Math.sin(rad) * r * rate;
      var y = r + Math.cos(rad) * r * rate;
      ctx.arc(x, y, 5, 0, 2 * Math.PI, false);
      ctx.closePath();
      ctx.fill();
    }
  };

  // 折线生长动画
  compontent.on('onLoad', function () {
    var s = 0;
    for (i = 0; i < 100; i++) {
      setTimeout(function () {
        s += .01;
        draw(s);
      }, i * 10);
    }
  });
  compontent.on('onLeave', function () {
    var s = 1;
    for (i = 0; i < 100; i++) {
      setTimeout(function () {
        s -= .01;
        draw(s);
      }, i * 10);
    }
  });


  return compontent;
};